<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JPG to PNG Converter</title>
    <style>
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            text-align: center;
        }

        #preview {
            max-width: 100%;
            margin: 20px 0;
        }
    </style>
</head>
<!-- http://127.0.0.1:5500/media%E5%A4%84%E7%90%86/image-converter/convert-to-png.html -->

<body>
    <div class="container">
        <!-- <h1>JPG 转 PNG 转换器</h1> -->
        <input type="file" id="fileInput" accept=".jpg,.jpeg">
        <br>
        <img id="preview" style="display: none;">
        <br>
        <a id="downloadLink" style="display: none;">
            <button>下载 PNG 图片</button>
        </a>
    </div>

    <script>
        const fileInput = document.getElementById('fileInput');
        const preview = document.getElementById('preview');
        const downloadLink = document.getElementById('downloadLink');

        fileInput.addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function (event) {
                preview.src = event.target.result;
                preview.style.display = 'block';

                // 当图片加载完成后进行转换
                preview.onload = function () {
                    const canvas = document.createElement('canvas');
                    // 使用原始图片尺寸，确保不会损失分辨率
                    canvas.width = preview.naturalWidth;
                    canvas.height = preview.naturalHeight;

                    const ctx = canvas.getContext('2d');
                    // 设置图像平滑度为高质量
                    ctx.imageSmoothingEnabled = true;
                    ctx.imageSmoothingQuality = 'high';
                    ctx.drawImage(preview, 0, 0);

                    // 转换为 PNG，使用最高质量设置
                    const pngUrl = canvas.toDataURL('image/png', 1.0);

                    // 设置下载链接
                    downloadLink.href = pngUrl;
                    downloadLink.download = file.name.replace(/\.(jpg|jpeg)$/i, '.png');
                    downloadLink.style.display = 'inline-block';
                };
            };
            reader.readAsDataURL(file);
        });
    </script>
</body>

</html>